#!/usr/bin/perl

use strict;

use EP::Config;
use EP::Common::Data;

use EP::Common::DBI::Session;
use EP::Common::DBI::Dataset;

# look for sessions that have been expired for at least 30 minutes
my @expired_sessions = EP::Common::DBI::Session->search_where (
  { "expire - (sysdate - cast('01-JAN-1970' as date)) * 86400" => { '<=', -30*60 } } );

warn "Found " . scalar @expired_sessions . " expired sessions.\n";
warn "Cleaning up...\n" if @expired_sessions > 0;

foreach my $s ( @expired_sessions ) {
  warn "Cleaning up session $s, owner " . $s->owner->username . "\n" if $s->owner;
  warn "Cleaning up uninited session $s\n" if not $s->owner;

  # if no owner set - the user never logged in, no files generated - just remove the session
  if ( not ( $s->owner ) ) {
    $s->delete;
  } else {
    # if user is guest, completely remove everything for that session
    if ( $s->owner->username eq "guest" ) {
      my ( @datasets ) = EP::Common::DBI::Dataset->search ( ep_session => $s->id );
      foreach my $d ( @datasets ) {
        EP::Common::Data::delete_dataset ( $d->id );
        $d->delete;
      }
      $s->delete;
    } else {
      $s->delete;
    }
  }
}
